package com.itcast.plane.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.internal.StringUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

@Service
public class HttpClientUtil {

    private static final String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx705e07561f374f84&secret=99abc0b250be220a767c7a314dc4c2d2&js_code=";
    private static final String uri = "&grant_type=authorization_code";

    public String doGet(String code){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url+code+uri);
            CloseableHttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String text = EntityUtils.toString(entity);
            System.out.println(text);
            JSONObject jsonObject = JSON.parseObject(text);
            String openid = jsonObject.get("openid").toString();
            if (StringUtil.isNullOrEmpty(openid)){
                return "false";
            }else {
                return openid;
            }
        }catch (Exception e){
            e.printStackTrace();
            return "false";
        }
    }

}
